package leetcode.leetcode_56;

import java.util.ArrayList;
import java.util.Arrays;

class Solution {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals,(p,q)->p[0]-q[0]);
        ArrayList<int[]> list = new ArrayList<>();
        for (int [] interval:intervals){
            if (list.size()!=0 && list.get(list.size()-1)[1]>=interval[0]){
                list.get(list.size()-1)[1]= Math.max(list.get(list.size()-1)[1],interval[1]);
            }
            else{
                list.add(interval);
            }
        }
        return list.toArray(new int[list.size()][]);
    }
}